using Unity.Profiling;
using Unity.Profiling.Editor;
using UnityEditorInternal;
using UnityEngine;

namespace SGEngine.ProfilerEx
{
    [ProfilerModuleMetadata("GC统计")]
    public class ProfilerGCModule : ProfilerModule
    {
        private static bool s_IsEventListened = false;
        private static readonly ProfilerCounterDescriptor[] k_Counter = new[]
        {
            new ProfilerCounterDescriptor("GC Allocation In Frame Count", ProfilerCategory.Memory)
        };

        public ProfilerGCModule() : base(k_Counter)
        {
            AddEventListened();
        }

        public override ProfilerModuleViewController CreateDetailsViewController()
        {
            return new ProfilerGCViewController(ProfilerWindow);
        }
        
        #region 事件
        private void AddEventListened()
        {
            if (!s_IsEventListened)
            {
                s_IsEventListened = true;
                ProfilerDriver.profileLoaded += OnProfileLoaded;
                ProfilerDriver.profileCleared += OnProfileCleared;
                ProfilerDriver.NewProfilerFrameRecorded += OnNewProfilerFrameRecorded;
            }
        }
        
        private void OnProfileLoaded()
        {
            ProfilerExData.Instance.LoadDataByProfilerData();
        }

        private void OnProfileCleared()
        {
            ProfilerExData.Instance.Clear();
        }

        private void OnNewProfilerFrameRecorded(int connectionId, int newFrameIndex)
        {
            ProfilerExData.Instance.MergeNewProfilerFrameRecorded(newFrameIndex);
        }
        #endregion
    }
}